package com.leo.javase.thread.itcast;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 三个线程之间的通信
 * @author Lian
 */
public class ThreeThreadCommunication {
	
	public static void main(String[] args) {
		final Business1 bs = new Business1();
		
		//子线程1
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<5; i++){
					bs.sub2(i);
				}
			}
		}).start();
		
		//子线程12
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<5; i++){
					bs.sub3(i);
				}
			}
		}).start();
		
		//主线程
		for(int i=0; i<5; i++){
			bs.sub1(i);
		}
	}

}

class Business1{
	private Integer flag = 1;
	
	private Lock lock = new ReentrantLock();
	
	Condition condition1 = lock.newCondition();
	Condition condition2 = lock.newCondition();
	Condition condition3 = lock.newCondition();
	
	/**
	 * 主线程
	 * @param i
	 */
	public void sub1(int i){
		lock.lock();
		try{
			while(flag!=1){
				try {
					condition1.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			for(int j=0; j<4; j++){
				System.out.println("Main thread i="+(i+1)+",j="+(j+1));
			}
			
			flag = 2;
			condition2.signal();
		}finally{
			lock.unlock();
		}
	}
	
	/**
	 * 子线程2
	 * @param i
	 */
	public void sub2(int i){
		lock.lock();
		try{
			while(flag!=2){
				try {
					condition2.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int j=0; j<8; j++){
				System.out.println("Sub1 thread i="+(i+1)+",j="+(j+1));
			}
			
			flag = 3;
			condition3.signal();
		}finally{
			lock.unlock();
		}
	}
	/**
	 * 子线程3
	 * @param i
	 */
	public void sub3(int i){
		lock.lock();
		try{
			while(flag!=3){
				try {
					condition3.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int j=0; j<12; j++){
				System.out.println("Sub2 thread i="+(i+1)+",j="+(j+1));
			}
			
			flag = 1;
			condition1.signal();
		}finally{
			lock.unlock();
		}
	}
	
}
